package id.zelory.compressor.sample;

import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.app.Context;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Logger;

/**
 * Created on : June 18, 2016
 * Author     : zetbaitsu
 * Name       : Zetra
 * GitHub     : https://github.com/zetbaitsu
 */
class FileUtil {
    private static final int EOF = -1;
    private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;

    private FileUtil() {
    }

    public static File from(Context context, Uri uri) throws DataAbilityRemoteException, IOException {
        DataAbilityHelper helper = DataAbilityHelper.creator(context, uri);
        FileDescriptor fd = helper.openFile(uri, null);
        InputStream inputStream = new FileInputStream(fd);
        String fileName = getFileName(context, uri);
        String[] splitName = splitFileName(fileName);
        File tempFile = File.createTempFile(splitName[0], splitName[1]);
        tempFile = rename(tempFile, fileName);
        tempFile.deleteOnExit();
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(tempFile);
            if (inputStream != null) {
                copy(inputStream, out);
            }
        } catch (FileNotFoundException e) {
            Logger.getLogger(FileUtil.class.getName()).info("file not found");
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (out != null) {
                out.close();
            }
        }
        return tempFile;
    }

    private static String[] splitFileName(String fileName) {
        String name = fileName;
        String extension = "";
        int flag = fileName.lastIndexOf(".");
        if (flag != -1) {
            name = fileName.substring(0, flag);
            extension = fileName.substring(flag);
        }
        return new String[]{name, extension};
    }

    private static String getFileName(Context context, Uri uri) {
        String result = null;
        if (result == null) {
            result = uri.getDecodedPath();
            int cut = result.lastIndexOf(File.separator);
            if (cut != -1) {
                result = result.substring(cut + 1);
            }
        }
        return result;
    }

    private static File rename(File file, String newName) {
        File newFile = new File(file.getParent(), newName);
        if (!newFile.equals(file)) {
            if (newFile.exists() && newFile.delete()) {
                Logger.getLogger(FileUtil.class.getName()).info("Delete old " + newName + " file");
            }
            if (file.renameTo(newFile)) {
                Logger.getLogger(FileUtil.class.getName()).info("Rename file to " + newName);
            }
        }
        return newFile;
    }

    private static long copy(InputStream input, OutputStream output) throws IOException {
        long count = 0;
        int num;
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        while (EOF != (num = input.read(buffer))) {
            output.write(buffer, 0, num);
            count += num;
        }
        return count;
    }
}
